import "./reset.css";
import dayjs from "dayjs";
import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps, RoleFormItemProps } from "../utils/types";
import {
  getKeyList,
  isAllEmpty,
  hideTextAtIndex,
  deviceDetection
} from "@pureadmin/utils";
import {
  getRoleIds,
  getUserList,
  getAllRoleList, resetUserInfo, getRoleList, getDictValueList, getDictCateList, getRateList
} from "@/api/system";
import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  watch,
  computed,
  reactive,
  onMounted
} from "vue";
import {any} from "vue-types";

export function useDict(tableRef: Ref, treeRef: Ref) {
  const form = reactive({
    // 左侧部门树的id
    dict_id: "",
    label: "",
    value: "",
    keyword: "",
    status: ""
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const selectCateId = ref('0');
  const dataList = ref([]);
  const cateList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const treeLoading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,pageSizes: [20, 40, 60,100,300,500],
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "ID",
      prop: "id",
      width: 90
    },
    {
      label: "数据分类",
      prop: "cate.name",
      width: 130
    },
    {
      label: "值编号",
      prop: "label",
      minWidth: 130
    },
    {
      label: "值名称",
      prop: "value",
      minWidth: 130,showOverflowTooltip:true,
    },
    {
      label: "附加信息",
      prop: "value2",
      minWidth: 130,showOverflowTooltip:true,
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={2}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "created_at"
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.label
      }</strong>选项吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        // switchLoadMap.value[index] = Object.assign(
        //   {},
        //   switchLoadMap.value[index],
        //   {
        //     loading: true
        //   }
        // );
        // setTimeout(() => {
        //   switchLoadMap.value[index] = Object.assign(
        //     {},
        //     switchLoadMap.value[index],
        //     {
        //       loading: false
        //     }
        //   );
        //   message("已成功修改选项状态", {
        //     type: "success"
        //   });
        // }, 300);
        getDictValueList(row,"put").then(res=>{
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message(`已${row.status === 2 ? "停用" : "启用"}${row.label}选项`, {
            type: "success"
          });
        })
      })
      .catch(() => {
        row.status === 2 ? (row.status = 1) : (row.status = 2);
      });
  }

  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    // onSearch();
    getDictValueList({id:row.id},"delete").then(res=>chores(row,res,'删除',()=>{}))
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val
    onSearch()
  }


  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    getDictValueList({},"delete").then(res=>function (){
      message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
        type: "success"
      });
      tableRef.value.getTableRef().clearSelection();
      onSearch();
    })
  }

  async function onSearch() {
    loading.value = true;
    form.page = pagination.currentPage
    form.limit = pagination.pageSize
    const { data } = await getDictValueList(toRaw(form));

    dataList.value = data.data;
    pagination.total = data.total;
    pagination.pageSize = data.per_page;
    pagination.currentPage = data.from;
    console.log(4444,data,data.total)
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    form.dic_id = "";
    onSearch();
  };

function switchDict(id){
  form.dic_id = id;
  selectCateId.value = id;
  onSearch();
}

  function chores(curData,res,title,done) {
    if(res.code===0){
      message(`您${title}了选项名称为${curData.label}的这条数据`, {
        type: "success"
      });
      done(); // 关闭弹框
      onSearch(); // 刷新表格数据
    }else{
      message(`${title}失败，原因：${res.message}`, {
        type: "error"
      });
    }
  }
  function openDialog(cateList,title = "新增", row?: FormItemProps) {

    addDialog({
      title: `${title}选项`,
      props: {
        formInline: {
          title,
          dic_id: row?.dic_id ?? selectCateId.value,
          label: row?.label ?? "",
          value: row?.value ?? "",
          value2: row?.value2 ?? "",
          status: row?.status ?? 1,
          cateList:cateList??[]
        }
      },
      width: "46%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        // function chores() {
        //   message(`您${title}了用户名称为${curData.username}的这条数据`, {
        //     type: "success"
        //   });
        //   done(); // 关闭弹框
        //   onSearch(); // 刷新表格数据
        // }
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData,title);
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              getDictValueList(curData,"post").then(res=>chores(curData,res,title,done))
            } else {
              curData.id = row.id
              // 实际开发先调用修改接口，再进行下面操作
              getDictValueList(curData,"put").then(res=>chores(curData,res,title,done))
            }
          }
        });
      }
    });
  }


  watch(
    pwdForm
  );


  onMounted(async () => {
    onSearch();

    // 归属部门
    const { data } = await getDictCateList();
    cateList.value = data.data
  });

  return {
    form,getDictValueList,getDictCateList,
    loading,
    columns,
    dataList,
    treeLoading,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,cateList,switchDict,selectCateId,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
  };
}
